'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 签到
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var _ = require('lodash');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var PlayerManager = require('../../../libs/playerManager');
var dataApi = require('../../../libs/dataApi');
var rewardService = require('../../../services/rewardService');
var roleService = require('../../../services/roleService');
var genRewardService = require('../../../services/genRewardService');
var activityService = require('../../../services/activityService');
var actType = require('../../../consts/activityType.js');
var vipConf = require('../../../config/vipConf.js');
var constantUtil = require('../../../util/constantUtil.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 每日签到
 */
Handler.prototype.sign = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var reward = {};
    var num = 1;

    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['check', 'bag', 'role', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var check_model = player_manager.check;
                var check_info = _addCheck(check_model, 1);

                if (check_info.code !== Code.OK) {
                    return next(null, {
                        code: check_info.code
                    });
                }

                var check_day = check_info.check_day;

                // 是否签到
                if (check_day === 0) {
                    return next(null, {
                        code: Code.CHECK_HAVE_EXIST
                    });
                }

                var job_type = role_model.getJob();
                reward = _getCheckReward(job_type, check_day);
                if (!reward) {
                    return next(null, {
                        code: Code.CHECK_NOT_EXIST
                    });
                }

                if (role_model.getVip() >= reward.vip_lv) {
                    var vip_double = reward.vip_double;
                    if (!!vip_double) {
                        num = 2;
                    }
                    reward.reward_num *= num;
                    rewardService.addRewardToRole(player_manager, reward, moduleType.MDL_ACT_CHECK, operationType.OPR_ACT_CHECK_SIGN);
                } else {
                    rewardService.addRewardToRole(player_manager, reward, moduleType.MDL_ACT_CHECK, operationType.OPR_ACT_CHECK_SIGN);
                }

                player_manager.save(cb);
                activityService.push(role_id, actType.CHECK, player_manager);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    reward: reward,
                    vip_multiple: num
                }
            });
        }
    );
};

/**
 * 补签
 */
Handler.prototype.retry = function (msg, session, next) {
    var role_id = session.uid;
    var player_manager = new PlayerManager(role_id);
    var reward = {};
    var num = 1;
    // jshint maxstatements:100
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['check', 'bag', 'role', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var check_model = player_manager.check;
                var role_model = player_manager.role;

                var total_check_day = check_model.getTotalCheckDay();
                var curr_day = parseInt(moment().format('D'));

                // 本月签到已累计到这天
                if (total_check_day >= curr_day) {
                    return {
                        code: Code.CHECK_DAY_EXCEEDED
                    };
                }

                // 是否钻石足够
                var total_retry_check = check_model.getTotalRetryCheck();
                var diamond_num = _getSubDiamond(total_retry_check + 1);
                if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_CHECK, operationType.OPR_ACT_CHECK_RETRY, diamond_num)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                var check_info = _addCheck(check_model, 2);

                if (check_info.code !== Code.OK) {
                    return next(null, {
                        code: check_info.code
                    });
                }

                var check_day = check_info.check_day;
                var job_type = role_model.getJob();
                reward = _getCheckReward(job_type, check_day);

                if (!reward) {
                    return next(null, {
                        code: Code.CHECK_NOT_EXIST
                    });
                }

                if (role_model.getVip() >= reward.vip_lv) {
                    var vip_double = reward.vip_double;
                    if (!!vip_double) {
                        num = 2;
                    }
                    reward.reward_num *= num;
                    rewardService.addRewardToRole(player_manager, reward, moduleType.MDL_ACT_CHECK, operationType.OPR_ACT_CHECK_RETRY);
                } else {
                    rewardService.addRewardToRole(player_manager, reward, moduleType.MDL_ACT_CHECK, operationType.OPR_ACT_CHECK_RETRY);
                }

                player_manager.save(cb);
                activityService.push(role_id, actType.CHECK, player_manager);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward: reward,
                    vip_multiple: num
                }
            });
        }
    );
};

/**
 * 添加到签到列表
 * @param  {[type]} check_status [状态: 1签到/2补签]
 * @return {[type]}              [description]
 */
var _addCheck = function (check_model, check_status) {
    var total_check_day = check_model.getTotalCheckDay();
    var pre_check_day = check_model.getPreCheckDay() || 0;
    var check_day = check_model.getNextCheckDay();
    var curr_day = parseInt(moment().format('D'));
    var deny_check_day = check_model.deny_check_day;

    // 当天已签到
    if (check_status === 1 && pre_check_day >= curr_day) {
        return {
            code: Code.CHECK_HAVE_EXIST
        };
    }

    // 当前剩余可签到/补签天数
    var remain_check_day = curr_day - total_check_day - deny_check_day;
    if (remain_check_day <= 0) {
        return {
            code: Code.CHECK_DAY_EXCEEDED
        };
    }

    check_model.addCheck(check_status);

    return {
        code: Code.OK,
        check_day: check_day
    };
};

/**
 * 获取签到奖励
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _getCheckReward = function (job_type, check_day) {
    var check_month = parseInt(moment().format('M'));
    var key = job_type * 100 + check_month;
    var check_conf = dataApi.check.findById(key);
    var reward = {};
    _.some(check_conf, function (check_conf) {
        if (check_conf.day == check_day) {
            reward = genRewardService.generateRewardVip(check_conf);
            return true;
        }
    });
    return reward;
};

/**
 * 获取补签消耗钻石
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _getSubDiamond = function (check_day) {
    var remedy_check_conf = dataApi.remedy_check.findById(check_day);
    return remedy_check_conf.price;
};
